<?php
require_once __DIR__ . '/../functions.php';

header('Content-Type: application/json');

// 检查登录
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$userInfo = getUserInfo();
$orderId = intval($_GET['id'] ?? 0);

if ($orderId <= 0) {
    echo json_encode(['success' => false, 'message' => '订单ID无效']);
    exit;
}

$db = getDB();

// 如果是管理员，可以查看任何订单；否则只能查看自己的订单
if (isAdmin()) {
    $stmt = $db->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->execute([$orderId]);
} else {
    $stmt = $db->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ?");
    $stmt->execute([$orderId, $userInfo['id']]);
}

$order = $stmt->fetch();

if (!$order) {
    echo json_encode(['success' => false, 'message' => '订单不存在']);
    exit;
}

// 获取结算操作记录
$stmt = $db->prepare("SELECT oo.*, u.username as admin_name 
                     FROM order_operations oo 
                     LEFT JOIN users u ON oo.admin_id = u.id 
                     WHERE oo.order_id = ? 
                     ORDER BY oo.created_at DESC");
$stmt->execute([$orderId]);
$operations = $stmt->fetchAll();

// 处理操作记录的截图
foreach ($operations as &$op) {
    if (!empty($op['screenshots'])) {
        $screenshots = json_decode($op['screenshots'], true);
        $op['screenshot_urls'] = [];
        if (!empty($screenshots)) {
            foreach ($screenshots as $screenshot) {
                $op['screenshot_urls'][] = UPLOAD_URL . 'settlements/' . $screenshot;
            }
        }
    }
}

// 添加到返回数据中
$order['operations'] = $operations;
$order['settlement_type_label'] = getSettlementTypeText($order['settlement_type']);
$order['is_registered_label'] = getOrderRegistrationText($order['is_registered']);
$order['is_returned_label'] = getOrderReturnText($order['is_returned']);

// 处理图片URL
if ($order['order_screenshot']) {
    $order['screenshot_url'] = UPLOAD_URL . 'orders/' . $order['order_screenshot'];
}

if ($order['settlement_screenshot']) {
    $order['settlement_screenshot_url'] = UPLOAD_URL . 'settlements/' . $order['settlement_screenshot'];
}

// 获取配置选项标签
$order['delivery_location_label'] = getConfigOptionLabel('delivery_location', $order['delivery_location']);
$order['order_platform_label'] = getConfigOptionLabel('order_platform', $order['order_platform']);
$order['payment_method_label'] = getPaymentMethodText($order['payment_method']);

// 确保取件码字段存在
$order['pickup_code'] = $order['pickup_code'] ?? '';

echo json_encode(['success' => true, 'data' => $order]);
?>